﻿using System;
using System.Web;
using System.Web.Handlers;

namespace Caramel.Web
{
	public class UnitOfWorkPerRequestModule : IHttpModule
	{
		#region IHttpModule Members

		public void Init(HttpApplication context)
		{
			context.BeginRequest += this.OnBeginRequest;
			context.EndRequest += this.OnEndRequest;
		}

		public void Dispose()
		{
		}

		#endregion

		private void OnBeginRequest(object sender, EventArgs e)
		{
			//var application = sender as HttpApplication;

			//if (
			//    (application != null) ||
			//    (application.Context == null) ||
			//    (application.Context.Handler == null) ||
			//    (application.Context.Handler is AssemblyResourceLoader) ||
			//    (application.Context.Handler is DefaultHttpHandler)
			//    )
			//{
			//    return;
			//}

			HttpContext.Current.Items.Add("RequestUnitOfWork", UnitOfWork.Begin());
		}

		private void OnEndRequest(object sender, EventArgs e)
		{
			var work = HttpContext.Current.Items["RequestUnitOfWork"] as IUnitOfWork;

			if ((work != null) && (!work.WasCommitted) && (!work.WasRolledBack))
			{
				work.Commit();
				work.Dispose();
			}
		}
	}
}
